import React from 'react'
import { connect } from 'react-redux'
import { messages } from "share/common"
import TagSelect from 'ant-design-pro/lib/TagSelect'
import { Form, Modal, Spin, List, message } from 'antd'
const ListItem = List.Item;

import workflowService from 'containers/setting/workflow/workflow.service'
import workflowUtil from 'containers/setting/new-workflow/utils'
class NewAddApproveRuleModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      formFieldList: null, //表单条件字段 字段类型(100默认, 101文本, 102整数, 103日期, 104浮点数, 105日期, 106值列表, 107GPS, 108布尔)
      formFieldCostCenterList: null, //审批条件为成本中心属性字段
      chosenRuleOIDs: [],
    }
  }

  componentDidMount() {
    this.setState({
      formFieldList: this.props.formFieldList
    }, () => {
      this.getList();
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ chosenRuleOIDs: nextProps.defaultValue || [] });
    this.setState({
      formFieldList: nextProps.formFieldList
    }, () => {
      this.getList()
    });
  }

  getList = () => {
    //初始化审批条件的成本中心属性字段
    let formFieldList = this.state.formFieldList;
    let costCenterList = [];
    let costCenterPropertyList = [];
    Object.keys(formFieldList).map(key => {
      //拿出成本中心的名字
      if (key === '101' && formFieldList[key] && formFieldList[key].length) {
        formFieldList[key].map(field => {
          if (field.messageKey === 'select_cost_center' && field.dataSource) {
            let oneCostCenter = {};
            oneCostCenter.name = field.fieldName;
            oneCostCenter.refCostCenterOID = JSON.parse(field.dataSource).costCenterOID;
            costCenterList.push(oneCostCenter)
          }
        })
      }
      if (key === '300' && formFieldList[key] && formFieldList[key].length) {
        costCenterPropertyList = formFieldList[key];
      }
    });
    //把成本中心属性拼到对应的成本中心下
    costCenterList.map(costCenter => {
      costCenter.propertyList = [];
      costCenterPropertyList.map(property => {
        if (costCenter.refCostCenterOID === property.refCostCenterOID) {
          property.costCenterName = costCenter.name;
          costCenter.propertyList.push(property);
        }
      })
    });
    this.setState({ formFieldCostCenterList: costCenterList })
  };

  //判断条件类型
  checkNewRemarkType = (remark) => {
    return workflowService.checkNewRemarkType(remark);
  };


  //点击"确定"
  handleOK = () => {
    const { chosenRuleOIDs } = this.state;
    const { formFieldList } = this.state;
    let list = [];
    let chosenRuleItems = [];
    Object.keys(formFieldList).map(key => {
      (formFieldList[key]).map(item => {
        list.push(item)
      })
    });
    chosenRuleOIDs.map((oid, index) => {
      list.map(item => {
        if (item.markOID === oid) {
          let param = {
            index,
            entityOID: this.props.ruleApproverOID,
            conditionOID: workflowUtil.getRandomUUID(),
            name: item.fieldName,
            remark: item.messageKey,
            field: item.fieldOID,
            isEdit: true,
          };
          item.fieldContent && (param.fieldContent = item.fieldContent);
          let symbol = null;
          switch(this.checkNewRemarkType(item.messageKey)) {
            case 'custList':
              symbol = (item.messageKey === 'default_department_path' || item.messageKey === 'custom_form_department_path') ? '9007' : '9009';
              break;
            case 'boolean':
              symbol = '9012';
              break;
            case 'text':
              symbol = '9007';
              break;
            case 'selector':
              symbol = '9009';
              break;
            default:
              symbol = '9011'; //'long' || 'double' || 'date' (范围)
          }
          item.messageKey === 'select_cost_center' && (param.customEnumerationOID = JSON.parse(item.dataSource || '{}').costCenterOID);
          if (item.messageKey === 'cust_list') {
            param.customEnumerationOID = JSON.parse(item.dataSource || '{}').customEnumerationOID;
            param.refCostCenterOID = item.refCostCenterOID;
            param.costCenterName = item.costCenterName;
          }
          if (item.messageKey === 'default_user_department_extend' || item.messageKey === 'custom_form_department_extend') {
            param.customEnumerationOID = JSON.parse(item.dataSource || '{}').customEnumerationOID;
            // param.customEnumerationOID = "b0a71585-1429-41ee-a7a8-2a40bda07879";
          }
          symbol && (param.symbol = symbol);
          chosenRuleItems.push(param)
        }
        if ((item.messageKey === 'default_expense_type_amount' || item.messageKey === 'default_each_one_expense_type_amount' || item.messageKey === 'default_average_amount') && item.messageKey === oid) {
          let param = {
            index,
            entityOID: this.props.ruleApproverOID,
            name: item.fieldName,
            remark: item.messageKey,
            field: null,
            isEdit: true,
          };
          let symbol = null;
          symbol = '9011';
          symbol && (param.symbol = symbol);
          chosenRuleItems.push(param)
        }
      })
    });
    this.props.onOk(chosenRuleItems, null)
  };

  render() {
    const { visible } = this.props;
    const { loading, formFieldCostCenterList, chosenRuleOIDs, formFieldList } = this.state;
    let customFormFieldList = [];
    if (formFieldList) {
      (formFieldList['101'] || []).map(item => customFormFieldList.push(item));
      (formFieldList['102'] || []).map(item => customFormFieldList.push(item));
      (formFieldList['103'] || []).map(item => customFormFieldList.push(item));
      (formFieldList['104'] || []).map(item => customFormFieldList.push(item));
      (formFieldList['105'] || []).map(item => customFormFieldList.push(item));
      (formFieldList['106'] || []).map(item => customFormFieldList.push(item));
      (formFieldList['108'] || []).map(item => customFormFieldList.push(item));
      (formFieldList['109'] || []).map(item => customFormFieldList.push(item));
    }
    //markOID是前端打的唯一标示 如果有增加去 new-workflow/utils.js
    return (
      <div className='add-approve-rule-modal'>
        <div className="select-rule-modal-container"/>
        <Modal title={messages('setting.key1284'/*请选择要添加的审批条件*/)}
               visible={visible}
               className="refactoring-modal"
               onOk={this.handleOK}
               onCancel={this.props.onCancel}>
          <Spin spinning={loading}>
            <List itemLayout="horizontal">
              <ListItem className="default-addition">
                <div>
                  <h4>{messages('setting.key1285'/*默认条件*/)}</h4>
                  <span>{messages('setting.key1286'/*部门：申请人的部门；法人实体：申请人的法人实体*/)}</span>
                  <TagSelect value={chosenRuleOIDs} onChange={value => {this.setState({ chosenRuleOIDs: value })}}>
                    {formFieldList && (formFieldList['100'] || []).map(item => {
                      return <TagSelect.Option value={item.markOID} key={item.markOID}>{item.fieldName}</TagSelect.Option>
                    })}
                  </TagSelect>
                </div>
              </ListItem>
              <ListItem className="default-addition">
                <div><h4>{messages('setting.key1287'/*表单自定义条件*/)}</h4></div>
                <TagSelect value={chosenRuleOIDs} onChange={value => {this.setState({ chosenRuleOIDs: value })}}>
                  {customFormFieldList.map(item => {
                    return <TagSelect.Option value={item.markOID}
                                             key={item.markOID}>{item.fieldName}</TagSelect.Option>
                  })}
                </TagSelect>
              </ListItem>
              {formFieldList && formFieldList['200'] && !!formFieldList['200'].length && (
                <ListItem>
                  <h4>{messages('setting.key1288'/*管控条件*/)}</h4>
                  <TagSelect value={chosenRuleOIDs} onChange={value => {this.setState({ chosenRuleOIDs: value })}}>
                    {formFieldList['200'].map(item => {
                      return <TagSelect.Option value={item.markOID}
                                               key={item.markOID}>{item.fieldName}</TagSelect.Option>
                    })}
                  </TagSelect>
                </ListItem>
              )}
              {formFieldCostCenterList && !!formFieldCostCenterList.length && (
                <ListItem>
                  <h4>{messages('setting.key1289'/*成本中心属性条件*/)}</h4>
                  {formFieldCostCenterList.map(costCenter => {
                    return (
                      <div key={costCenter.refCostCenterOID}>
                        <div>{costCenter.name}</div>
                        <TagSelect value={chosenRuleOIDs}
                                   onChange={value => {this.setState({ chosenRuleOIDs: value })}}>
                          {costCenter.propertyList.map(item => (
                            <TagSelect.Option value={`${item.markOID}`}
                                              key={`${item.markOID}`}>{item.fieldName}</TagSelect.Option>
                          ))}
                        </TagSelect>
                      </div>
                    )
                  })}
                </ListItem>
              )}
              {formFieldList && formFieldList['400'] && !!formFieldList['400'].length && (
                <ListItem>
                  <h4>{messages('setting.key1290'/*申请人=成本中心经理*/)}</h4>
                  <TagSelect value={chosenRuleOIDs} onChange={value => {this.setState({ chosenRuleOIDs: value })}}>
                    {/*由于【申请人=成本中心经理】和【表单自定义条件中的成本中心】的fieldOID一样，为了区分，在fieldOID后拼上remark*/}
                    {formFieldList['400'].map(item => (
                      <TagSelect.Option value={`${item.markOID}`}
                                        key={`${item.markOID}`}>{item.fieldName}</TagSelect.Option>
                    ))}
                  </TagSelect>
                </ListItem>
              )}
            </List>
          </Spin>
        </Modal>
      </div>
    )
  }
}

NewAddApproveRuleModal.propTypes = {
  visible: React.PropTypes.bool,
  formOID: React.PropTypes.string,
  ruleApproverOID: React.PropTypes.string,
  batchCode: React.PropTypes.number,
  defaultValue: React.PropTypes.array,
  onOk: React.PropTypes.func,
  onCancel: React.PropTypes.func,
  type: React.PropTypes.number,//条件类型 1条件 2条件组
  formFieldList: React.PropTypes.object,
};


NewAddApproveRuleModal.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const wrappedNewAddApproveRuleModal = Form.create()(NewAddApproveRuleModal);

export default connect(mapStateToProps)(wrappedNewAddApproveRuleModal)
